import axios from 'axios'
import router from '@/router'

axios.defaults.timeout = 100000000
axios.defaults.baseURL = process.env.API_HOST
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

// HTTP拦截器
axios.interceptors.request.use(
  config => {
    let username = localStorage.getItem('userName')
    config.headers.timestamp = username
    return config
  }, error => {
    return Promise.reject(error)
  })
axios.interceptors.response.use(
  response => {
    if (response.data.code === '001') {
      router.replace({
        path: '/login',
        query: {redirect: router.currentRoute.fullPath}
      })
    }
    return response
  }, error => {
    return Promise.reject(error)
  })

/*
* 封装get方法
* @param url
* @param data
* @param return {Promise}
* */
export function get (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export function post (url, data = {}, options) {
  return new Promise((resolve, reject) => {
    axios.post(url, data, options).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}
